<template>
  <div class="login">
    <van-nav-bar title="登录" />

    <van-form @submit="onSubmit">
      <van-field
        v-model="form.data.mobile"
        name="mobile"
        placeholder="请输入手机号"
        :rules="form.rules.mobile"
      >
        <template #left-icon>
          <i class="toutiao toutiao-shouji"></i>
        </template>
      </van-field>
      <van-field
        v-model="form.data.code"
        name="code"
        placeholder="请输入验证码"
        :rules="form.rules.code"
      >
        <template #left-icon>
          <i class="toutiao toutiao-yanzhengma"></i>
        </template>
        <template #button>
          <van-count-down v-if="isShowCountDown" :time="1000 * 5" @finish="isShowCountDown = false">
            <template #default="{ seconds }">
              {{ (seconds + 1 + '').padStart(2, '0') }} s
            </template>
          </van-count-down>
          <van-button
            v-show="!isShowCountDown"
            round
            size="small"
            type="primary"
            native-type="button"
            @click="sendSMS"
          >
            发送验证码
          </van-button>
        </template>
      </van-field>
      <div style="margin: 16px;">
        <van-button block type="info" native-type="submit">提交</van-button>
        <br />
        <br />
        <van-button block @click="testRefreshToken" native-type="button"
          >测试refresh_token</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
import { login, sendSMS, getUserChannels } from '../api/user.js'
export default {
  name: 'Login',
  data() {
    return {
      isShowCountDown: false,
      form: {
        data: {
          mobile: '',
          code: ''
        },
        rules: {
          mobile: [
            { required: true, message: '请输入手机号码' },
            { pattern: /^1[3578]\d{9}$/, message: '手机号码格式不正确' }
          ],
          code: [
            { required: true, message: '请输入验证码' },
            { pattern: /^\d{6}$/, message: '验证码格式不正确' }
          ]
        }
      }
    }
  },
  methods: {
    ...mapMutations(['setUser']),

    async testRefreshToken() {
      const { data: res } = await getUserChannels()
      console.log(res)
    },

    async sendSMS() {
      this.isShowCountDown = true
      await sendSMS(this.form.data.mobile)
      this.$toast.success('发送成功')
    },
    async onSubmit() {
      const { data: res } = await login(this.form.data)
      this.$toast.success('登录成功')
      console.log(res.data)
      // this.$store.commit('setUser', res.data)
      this.setUser(res.data)
    }
  }
}
</script>
